<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto"
        class="demo-ruleForm">
        <el-form-item label="原密码" prop="old_password">
            <el-input v-model="ruleForm.old_password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
            <el-input v-model="ruleForm.new_password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_password" type="password">
            <el-input v-model="ruleForm.re_password" autocomplete="off"/>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                确认更改
            </el-button>
            <el-button @click="resetForm(ruleFormRef)" type="info">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { updatePassword } from '../../api/service.js' 
import { useRouter } from 'vue-router';
const router = useRouter()
// import { ElMessage } from 'element-plus/lib/components/index.js';

interface RuleForm {
    old_password: string;
    new_password: string;
    re_password: string;
}

const ruleFormRef = ref<FormInstance>()

const ruleForm = ref<RuleForm>({
    old_password: '',
    new_password: '',
    re_password: '',
})

const rules = reactive<FormRules<RuleForm>>({
    old_password: [
        {required: true, message: '请输入原密码', trigger: 'blur'}
    ],
    new_password: [
        {required: true, message: '请输入新密码', trigger: 'blur'}
    ],
    re_password: [
        {required: true, message: '请确认密码', trigger: 'blur'}
    ]
});

const submitForm = async(formEl: FormInstance | undefined) => {
    console.log(ruleForm)
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
            if(ruleForm.value.new_password != ruleForm.value.re_password){
                alert('原密码和确认密码不一致')
            }
        } else {
            console.log('error submit!')
        }
    })

    const payload = {
        oldPassword: ruleForm.value.old_password,
        newPassword: ruleForm.value.new_password,
        rePassword: ruleForm.value.re_password
    } 

    const result = await updatePassword(payload);
    if(result.data.code === 200){
        ElMessage.success('密码修改成功');
        router.push('/login')
    }else{
        ElMessage.error('密码修改失败')
    }
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>